#coding=utf-8
import urllib2,urllib,urlparse
import socket,os,sys,re,md5,time
socket.setdefaulttimeout(60)

debug_level = 1
url = 'http://gw.api.taobao.com/router/rest'
app_key = '12022540'
app_secret = '6f7a04f813d9a9fc916e0b15854e9f6f'

def _sign(param, sercetCode):
	src = sercetCode + ''.join(["%s%s" % (k, v) for k, v in sorted(param.items())])
	return md5.new(src).hexdigest().upper()
	
class TopRobot(object):
    
  def __init__(self, app_key=app_key, app_secret=app_secret):
    self.app_key = app_key
    self.app_secret = app_secret
    
    #API系统级参数
    self.v = '2.0'
    self.format = 'json'
    
    self.opener = self._build_opener()

    #self._add_opener_header('user-agent', user_agent)
    #self._add_opener_header('referer', referer)
        
  def _add_opener_header(self, k, v):
    i = 0
    for x, y  in self.opener.addheaders:
        if x.lower() == k.lower():break
        i = i + 1
        
    if i < len(self.opener.addheaders):
        self.opener.addheaders.remove(self.opener.addheaders[i])
    self.opener.addheaders.append((k,v))
            
  def _build_opener(self):
    #cookie_support = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener( urllib2.HTTPHandler(debuglevel=debug_level) )#, cookie_support)
    return opener
  
  def fetch_data(self, post_data):
    post_data['app_key'] = self.app_key
    post_data['v'] = self.v
    post_data['format'] = self.format
    
    t = time.localtime()
    print time.strftime('%Y-%m-%d %X', t)
    post_data['timestamp'] = time.strftime('%Y-%m-%d %X', t)
    
    sign = _sign(post_data, self.app_secret)
    post_data['sign'] = sign
    
    print post_data
    form_data = urllib.urlencode(post_data)
    
    f = self.opener.open(url, form_data)
    code, resp, content = f.getcode(), f.info(), f.read()
    
    return code, resp, content
    
if __name__ == '__main__':

  import robot
  r = robot.TopRobot()
  post_data ={'method':'taobao.taobaoke.items.get','fields':'commission,commission_rate,commission_num,commission_volume,iid,title,nick,pic_url,price,click_url', 'nick':'xiaojay2006', 'cid':'1512'}
  code, r,c = r.fetch_data(post_data)
  print c

